package com.aotain.project.apollo;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.log4j.Logger;

import com.aotain.hbase.HBaseRecordAdd;
import com.aotain.apollo.utils.ApolloProperties;




/**
 * 
 * @author Administrator
 *
 */
public class SiteEvaluateMain {
	
	static SiteEvaluateMain singleton;

	private Configuration cfg = null;
	private Connection connection = null;
	String zooServer = "";
//	String driverServer = "";
//	String brokerList = "";
	
	static Object locker = new Object();
	 
	/**
	   * 2016/11/10  失效，请使用 SiteEvaluateMain(String zooServer) 方法，不再需要传值driver,broList
	   * @param zooServer
	   * @param driverServer
	   * @param brokerList
	   * @return
	   */
	  @Deprecated
	public SiteEvaluateMain(String zoo,String driver,String broList)
	{
		// 
		Configuration HBASE_CONFIG = HBaseConfiguration.create();
		HBASE_CONFIG.set("hbase.zookeeper.quorum", zoo);  //
		HBASE_CONFIG.set("hbase.zookeeper.property.clientPort","2181");	
		cfg = HBaseConfiguration.create(HBASE_CONFIG);
		try {
			connection = ConnectionFactory.createConnection(HBASE_CONFIG);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		zooServer = zoo;
//		driverServer = driver;
//		brokerList = broList;
		 
	}
	
	
	public SiteEvaluateMain(String zoo)
	{
		// 
		Configuration HBASE_CONFIG = HBaseConfiguration.create();
		HBASE_CONFIG.set("hbase.zookeeper.quorum", zoo);  //
		HBASE_CONFIG.set("hbase.zookeeper.property.clientPort","2181");	
		cfg = HBaseConfiguration.create(HBASE_CONFIG);
		try {
			connection = ConnectionFactory.createConnection(HBASE_CONFIG);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		zooServer = zoo;
//		driverServer = driver;
//		brokerList = broList;
		 
	}
	
//	 public static SiteEvaluateMain getInstance(String zooServer,String driverServer) {
//		  
//		  if (singleton == null) {
//		      synchronized (locker) {
//		    	  if (singleton == null) {
//		          singleton = new SiteEvaluateMain(zooServer,driverServer);
//		    	  }
//		      }
//		  }
//		  return singleton;
//	  }
	
	public static void main(String[] args){
		try{
			//String tablename="SDS_ABNORMAL_LOG";
			//String tablename="SDS_IDC_LOG";
			String tablename = args[0];
			String startrow = args[1];
			String endrow =  args[2];
			
			//
			

			//HbaseCommon.getData(tablename, startrow, endrow,10000);
			
			//HbaseCommon.getData(tablename, "101.227.160.27_2015092700", "101.227.160.27_2015092300");
			//HbaseCommon.getData(tablename, "101.227.130.26_2015092300", "101.227.130.26_2015092400");
			//HbaseCommon.getAllData(tablename);
			System.out.println("test");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public void EvaluateFunction(String IP,String StartDate,String EndDate,long PV)
	{
		Scan scan = new Scan();
        scan.setStartRow(Bytes.toBytes(String.format("%s_%s", IP, StartDate)));
        scan.setStopRow(Bytes.toBytes(String.format("%s_%s", IP, EndDate)));
        scan.addFamily(Bytes.toBytes("cf"));
        scan.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("PORTLOW"));
        scan.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("SESSIONMIDDLE"));
        scan.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("CC"));
        scan.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("DOS"));
        
        //
        String tableName = "SDS_ABN_SESS_STAT_H";
        
        HBaseRecordAdd hbaseInstance = HBaseRecordAdd.getInstance(zooServer);
        
        TableName TABLE_NAME = TableName.valueOf(tableName);
		try {
			
			if(connection == null)
				return;
			
			Table table = connection.getTable(TABLE_NAME);
			
			ResultScanner ss = table.getScanner(scan);
			double score = 0;
			int rownum = 0;
			Result r = null;
			while ((r = ss.next())!=null)
			{//
				
				long nPortPV = 0;
           		long nSessionPV = 0;
           		long nCC = 0;
           		long nDOS = 0;
			   
			
           		//Cell destIP = r.getColumnLatestCell(Bytes.toBytes("cf"), Bytes.toBytes("IP"));
           		Cell portPV = r.getColumnLatestCell(Bytes.toBytes("cf"), Bytes.toBytes("PORTLOW"));
              
           		if(portPV != null)
               		nPortPV = Bytes.toLong(CellUtil.cloneValue(portPV));
           		
           		Cell ccPV = r.getColumnLatestCell(Bytes.toBytes("cf"), Bytes.toBytes("CC"));
                
           		if(ccPV != null)
           			nCC = Bytes.toLong(CellUtil.cloneValue(ccPV));
           		
               
           		Cell sessionPV = r.getColumnLatestCell(
                       Bytes.toBytes("cf"), Bytes.toBytes("SESSIONMIDDLE"));
           		
           		Cell dosPV = r.getColumnLatestCell(
                        Bytes.toBytes("cf"), Bytes.toBytes("DOS"));
           		
               if(sessionPV != null)
               		nSessionPV = Bytes.toLong(CellUtil.cloneValue(sessionPV));
               
               if(dosPV != null)
            	   nDOS = Bytes.toLong(CellUtil.cloneValue(dosPV));
               rownum++;
               
               double sorceH = 100;
               
               if(nPortPV>0)
            	   sorceH = 80;
               if(nSessionPV > 0 )
            	   sorceH = 60;
               if(nDOS > 0 )
            	   sorceH = 40;
               if(nCC > 0 )
            	   sorceH = 40;
               
               hbaseInstance.Add(tableName, Bytes.toString(r.getRow()), "cf", "EVALUATE", String.valueOf(sorceH));
               
               
               score = sorceH + score;
			}
			ss.close();
			table.close();
			
			if(rownum == 0)
				score = 100;
			else
				score = score/rownum;
			
			
			
        	String destip = IP;
        	
			
			String rowkey = String.format("%s_%s", destip, StartDate);
			
			String tbName = "SDS_EVALUATE_SITE";
			
			hbaseInstance.Add(tbName, rowkey, "cf",  "IP", destip);
			hbaseInstance.Add(tbName, rowkey, "cf",  "REPORTTIME", StartDate);
			hbaseInstance.Add(tbName, rowkey, "cf", "EVALUATE", String.valueOf(score));
			hbaseInstance.incerment(tbName, rowkey, "cf:PV", PV);
			
			
//			String RevRowkey = String.format("%s_%s", StartDate, destip);
//			
//			
//			hbaseInstance.Add(tbName, RevRowkey, "cf",  "IP", destip);
//			hbaseInstance.Add(tbName, RevRowkey, "cf",  "REPORTTIME", StartDate);
//			hbaseInstance.Add(tbName, RevRowkey, "cf", "EVALUATE", String.valueOf(score));
//			hbaseInstance.incerment(tbName, RevRowkey, "cf:PV", PV);
			
			//hbaseInstance.ImmdiateFlashData();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		

	}
	
	
	/**
	 * IDC全网评估
	 * @param StartDate
	 * @param EndDate
	 */
	public void EvaluateIDC(String StartDate,String EndDate)
	{
		
		Scan scan = new Scan();
        scan.setStartRow(Bytes.toBytes(String.format("%s", StartDate)));
        scan.setStopRow(Bytes.toBytes(String.format("%s", EndDate)));
        scan.addFamily(Bytes.toBytes("cf"));
        scan.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("CHKNUM"));
        scan.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("ATTSITENUM"));
        
        System.out.println("START EvaluateIDC######################");
        //
        String tableName = "SDS_IDC_STAT_D";
        
        TableName TABLE_NAME = TableName.valueOf(tableName);
      	try {
      		Table table = connection.getTable(TABLE_NAME);
      			
      		ResultScanner ss = table.getScanner(scan);
      		double score = 0;
      		int nCHKNUM = 0;
            int nATTSITENUM = 0;
            
      		for (Result r : ss)
      		{//
                Cell cellCHKNUM = r.getColumnLatestCell(Bytes.toBytes("cf"), 
                		Bytes.toBytes("CHKNUM"));
                
                    
                if(cellCHKNUM != null && CellUtil.cloneValue(cellCHKNUM).length > 0)
                	nCHKNUM = Integer.parseInt(Bytes.toString(CellUtil.cloneValue(cellCHKNUM)));
                     
                Cell cellATTSITENUM = r.getColumnLatestCell(
                		Bytes.toBytes("cf"), Bytes.toBytes("ATTSITENUM"));
                if(cellATTSITENUM != null)
                	nATTSITENUM = Integer.parseInt(Bytes.toString(CellUtil.cloneValue(cellATTSITENUM)));
      		}
      		ss.close();
      		table.close();
      		
      		if(nCHKNUM!=0)
      			score = (nATTSITENUM/nCHKNUM)*100;
      			
      		if(score == 0)
      			score = 100;
      		
      		System.out.println("*****************START EvaluateIDC[score:" + score + "]");
      			
      		HBaseRecordAdd hbaseInstance = HBaseRecordAdd.getInstance(zooServer);
      			
      		String rowkey = String.format("%s", StartDate);
      		
      		int nSCANNUM = nCHKNUM - nATTSITENUM;
      			
      		String tbName = ApolloProperties.SDS_IDC_STAT_D;
      		hbaseInstance.Add(tbName, rowkey, "cf", "EVALUATE", String.valueOf(score));
      		hbaseInstance.Add(tbName, rowkey, "cf", "SCANNUM", String.valueOf(nSCANNUM));
      			
      		} catch (IOException e) {
      			// TODO Auto-generated catch block
      			Logger.getRootLogger().error(e);
      		}
      		
        
	}
	
	public void CloseConnection()
	{
		if(connection!=null)
		{
			try {
				connection.close();
				connection = null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
